import { defineStore } from 'pinia'
import { getArticles, getArticleDetail, getHomeRecommended, getHotArticles } from '@/api/article'

export const useArticleStore = defineStore('article', () => {
  // 状态
  const articles = ref([])
  const currentArticle = ref(null)
  const homeRecommended = ref({})
  const hotArticles = ref([])
  const loading = ref(false)

  // 获取文章列表
  const fetchArticles = async (params = {}) => {
    try {
      loading.value = true
      const { data } = await getArticles(params)
      articles.value = data?.list || []
      return data
    } catch (error) {
      console.error('获取文章列表失败:', error)
      return { list: [], total: 0 }
    } finally {
      loading.value = false
    }
  }

  // 获取文章详情
  const fetchArticleDetail = async (id) => {
    try {
      loading.value = true
      const { data } = await getArticleDetail(id)
      currentArticle.value = data
      return data
    } catch (error) {
      console.error('获取文章详情失败:', error)
      return null
    } finally {
      loading.value = false
    }
  }

  // 获取首页推荐内容
  const fetchHomeRecommended = async () => {
    try {
      const { data } = await getHomeRecommended()
      homeRecommended.value = data || {}
      return data
    } catch (error) {
      console.error('获取首页推荐内容失败:', error)
      return {}
    }
  }

  // 获取热门文章
  const fetchHotArticles = async (limit = 10) => {
    try {
      const { data } = await getHotArticles({ limit })
      hotArticles.value = data || []
      return data
    } catch (error) {
      console.error('获取热门文章失败:', error)
      return []
    }
  }

  return {
    articles,
    currentArticle,
    homeRecommended,
    hotArticles,
    loading,
    fetchArticles,
    fetchArticleDetail,
    fetchHomeRecommended,
    fetchHotArticles
  }
})